package com.gxa.modules.sys.controller;

import cn.hutool.core.codec.Base64;
import com.gxa.common.utils.*;
import com.gxa.modules.sys.entity.User;
import com.gxa.modules.sys.entity.UserBak;
import com.gxa.modules.sys.form.UserForm;
import com.gxa.modules.sys.redis.SysUserRedis;
import com.gxa.modules.sys.service.UserService;
import com.gxa.modules.sys.service.UserTokenService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Api(tags = "个人信息接口")
@RestController
@Slf4j
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private SysUserRedis sysUserRedis;
    @Autowired
    private UserTokenService userTokenService;

    //生成验证码返回图片,并且保存到redis
    @ApiOperation("获取验证码")
    @GetMapping(value = "/sys/getVerify")
    public Result getVerify(HttpServletResponse response)throws IOException {
        Result r = new Result();
        VerifyCodeUtil VerifyCodeUtils=new VerifyCodeUtil();
        String verifyCode = VerifyCodeUtils.generateVerifyCode(4);
        // 生成图片
        int w = 111, h = 36;
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        VerifyCodeUtils.outputImage(w, h, stream, verifyCode);
        UUID uuid = UUID.randomUUID();
        String key = uuid.toString();

        sysUserRedis.addCode(key,verifyCode);

        try {
            Map map=new HashMap<>();
            map.put("uuid", uuid);
            map.put("img", Base64.encode(stream.toByteArray()));
            return r.ok(map);
        } catch (Exception e) {
            e.printStackTrace();
            r.error();
        }
        return  r.ok();
    }


    @ApiOperation("用户登录")
    @PostMapping("/sys/login")
    public Result login(@RequestBody UserForm userFrom){

        log.info("user------->{}",userFrom);
        //验证码
        String userInputCaptch = userFrom.getCaptch();
        String uuid = userFrom.getUuid();

        String redisGetCaptch = this.sysUserRedis.getCode(uuid);

        System.out.println("从redis中查询到的验证码---->"+redisGetCaptch);
        System.out.println("用户数输入的验证码---->"+userInputCaptch);

        System.out.println("对比验证码-->"+redisGetCaptch.equals(userInputCaptch));

        if (!redisGetCaptch.equals(userInputCaptch)){
            return new Result().error(ErrorCode.ACCOUNT_PASSWORD_ERROR,"验证码不正确或者已经失效");
        }

        //1、拿着用户名去 查询用户信息
        User user = this.userService.queryByUsername(userFrom.getUsername());

        String state = user.getState();
        System.out.println("state------->"+state);
        if (!state.equals("1")){
            return new Result().error(ErrorCode.ACCOUNT_PASSWORD_ERROR,"该用户已经被禁用,请联系管理员");
        }

        if(user == null){
            return new Result().error(ErrorCode.ACCOUNT_PASSWORD_ERROR,"用户名不存在");
        }

        //2、通过明文加密  对比  密文 是否一致
//        String pwd = new SimpleHash("MD5", userFrom.getPassword(), user.getSalt(), 1024).toString();
        String pwd = new SimpleHash("MD5", userFrom.getPassword(), null, 1024).toString();
        System.out.println("加密后---->"+pwd);
        System.out.println("查询---->"+user.getPwd());
        //3、不一致      返回Result.error()
        if(!pwd.equals(user.getPwd())){
            return new Result().error(ErrorCode.ACCOUNT_PASSWORD_ERROR,"用户名或密码不正确");
        }

        //4、一致     生成token 保存redis中 返回Result.ok()
        Result result = this.userTokenService.createToken(user);
        Map map = new HashMap();
        map.put("token",result.getData());

        Integer id = user.getId();
        System.out.println("用户id---->"+id);

        String name = user.getName();


//        map.put("用户id",id);
//        map.put("用户名字",name);

        List<UserBak> rounting = this.userService.getUserByName(user.getUsername());
        map.put("rounting",rounting);

        return new Result().ok(map);
    }

//    @RequiresPermissions("list")
    @ApiOperation(value="当前登录用户信息 根据传入的ID")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query",name = "id",value ="用户ID",dataType ="String"),
    })
    @GetMapping("/user/list")
    public Result<PageUtils> Userlist(@RequestParam Map<String,Object> params){
        log.info("----params-----{}----",params);
        AssertUtils.isBlank(String.valueOf(params), "字符串不为能空");

        PageUtils pageUtils = this.userService.queryById(params);
        return new Result<PageUtils>().ok(pageUtils);
    }

    @ApiOperation(value="修改当前登录用户信息 根据传入的ID")
    @ApiImplicitParams({})
    @PutMapping("/user/update")
    public Result<PageUtils> UserEdit(@RequestBody User user){
        log.info("----user-----{}----",user);
        AssertUtils.isBlank(String.valueOf(user), "字符串不为能空");
        String pwd = user.getPwd();
        String pwdMd5 = new SimpleHash("MD5", pwd, null, 1024).toString();
        user.setPwd(pwdMd5);
        this.userService.updateUser(user);
        return new Result<PageUtils>().ok();
    }
    //退出
    @ApiOperation("用户退出")
    @GetMapping("/user/logout")
    @ResponseBody
    public String logout(HttpSession session){
        session.invalidate();

        return "redirect:/index.html";

    }

    @GetMapping( "/unauthorized")
    public com.gxa.modules.community.util.Result<String> unAuth(){
        com.gxa.modules.community.util.Result<String> r=com.gxa.modules.community.util.Result.failed("没有权限");
        r.setCode("1");
        System.out.println(r.getMsg());
        return r;
    }

}
